package main

import (
	"chat/common/msg"
	userProcess "chat/server/process"
	"chat/utils"
	"fmt"
	"io"
	"net"
)

type Process struct {
	Conn net.Conn
}

// 根据不同消息类型，调用不同方法
func (this *Process) serverPocessMsg(message *msg.Message) (err error) {
	switch message.Type {
	// 登录消息
	case msg.LoginMsgType:
		up := &userProcess.UserProcess{
			Conn: this.Conn,
		}
		err = up.ServerProcessLogin(message)

	// 注册消息
	case msg.RegisterMsgType:
		up := &userProcess.UserProcess{
			Conn: this.Conn,
		}
		err = up.ServerProcessRegister(message)
	// 群发消息
	case msg.SmsMesType:
		smsProcess := userProcess.SmsProcess{}
		smsProcess.SendGroupMes(message)

	default:
		fmt.Println("消息类型错误=", message)
	}
	return
}

func (this *Process) process() (err error) {
	// 循环读取消息
	for {
		// 读取数据封装成readPkg
		tf := &utils.Transfer{
			Conn: this.Conn,
		}
		msg, err := tf.ReadPkg()
		if err != nil {
			if err == io.EOF {
				fmt.Println("客户端关闭")
				return err
			} else {
				fmt.Println("readPkg error = ", err)
				return nil
			}
		}
		fmt.Println("readPkg msg = ", msg)
		err = this.serverPocessMsg(&msg)
		if err != nil {
			fmt.Println("serverPocessMsg err = ", err)
		}
	}

}
